﻿using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Model.EnumUtil;
using Estsh.Core.Models;
using Estsh.Core.Services;
using Estsh.Core.Wms.IRepositories;
using Estsh.Core.Wms.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Estsh.Core.Wms.Services
{
    /// <summary>
    /// 销售发运
    /// </summary>
    public class SaleDeliveryService : BaseService<BaseEntity>, ISaleDeliveryService
    {
        private readonly ISaleDeliveryRepository repository;
        public SaleDeliveryService(ISaleDeliveryRepository _repository) : base(_repository)
        {
            repository = _repository;
        }
        public SetObjectDetail GetSaleDeliveryOrderList(string orderNo)
        {
            SetObjectDetail rfInfo = new SetObjectDetail();//返回消息
            List<WmsOutstock> wmsMoves = repository.GetSaleDeliveryOrderList(orderNo);

            if (wmsMoves.Count > 0)
            {
                rfInfo.type = "PASS";
                rfInfo.message = "成功";
                rfInfo.wmsObjectDetail = wmsMoves.ConvertAll(s => (object)s);
            }
            else
            {
                rfInfo.type = "FAIL";
                rfInfo.message = "未查询到数据，请检查！";
            }
            return rfInfo;
        }
        public SetObjectDetail GetSaleDeliveryOrderListByOrderNo(string orderNo)
        {
            SetObjectDetail rfInfo = new SetObjectDetail();
            List<WmsOutstock> wmsMoves = repository.GetSaleDeliveryOrderListByOrderNo(orderNo);
            if (wmsMoves.Count > 0)
            {
                rfInfo.type = "PASS";
                rfInfo.message = "成功";
                rfInfo.wmsObjectDetail = wmsMoves.ConvertAll(s => (object)s);
            }
            else
            {
                rfInfo.type = "FAIL";
                rfInfo.message = "未查询到数据，请检查！";
            }
            return rfInfo;
        }

        public SetObjectDetail CheckStockByCartonAlocate(string cartonNo, string orderNo, string isGroup, string loginId)
        {
            SetObjectDetail rfInfo = new SetObjectDetail();
            List<SysStock> sysStocks = repository.GetStockInfoByCartonNo(cartonNo);

            if (sysStocks.Count == 0)
            {
                //提示  [M0090105]:该条码不可用，请检查!
                rfInfo.type = "FAIL";
                rfInfo.message = "[" + cartonNo + "]:该条码不存在，请检查!";
                return rfInfo;
            }
            else if (sysStocks[0].Enabled != "Y")
            {
                //提示  [M0090105]:箱条码已冻结，无法操作!
                rfInfo.type = "FAIL";
                rfInfo.message = "[" + cartonNo + "]:箱条码已冻结，无法操作!";
                return rfInfo;
            }
            else if (sysStocks[0].Status != (int)WmsEnumUtil.StockStatus.BATCHED)
            {
                //提示  [M0090105]:该条码未配料，请检查!";
                rfInfo.type = "FAIL";
                rfInfo.message = "[" + cartonNo + "]:该条码未配料，请检查!";
                return rfInfo;
            }


            List<WmsOutstock> WmsOutstocks = repository.GetOutStockByOrderNo(orderNo);
            if (WmsOutstocks.Count == 0)
            {
                rfInfo.type = "FAIL";
                rfInfo.message = "[" + orderNo + "]:该单据是未创建或已关闭状态，请检查!";
                return rfInfo;
            }

            if (isGroup == "1")
            {
                if (string.IsNullOrEmpty(sysStocks[0].GroupNo) || sysStocks[0].GroupNo == "NULL")
                {
                    rfInfo.type = "FAIL";
                    rfInfo.message = "[" + cartonNo + "]:分组号不能为空，请检查!";
                    return rfInfo;
                }
                sysStocks = repository.GetStockByGroupNo(sysStocks[0].GroupNo);
            }

            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();
            StringBuilder stringBuilder = new StringBuilder();
            for (int k = 0; k < sysStocks.Count; k++)
            {
                List<WmsOutstockDetail> WmsOutstockDetails = repository.GetOutStockDetailByOrderPartNo(orderNo, sysStocks[k].PartNo);
                if (WmsOutstockDetails.Count == 0)
                {
                    //提示  [M0090105]:该条码是NC入库状态，无法操作!
                    rfInfo.type = "FAIL";
                    rfInfo.message = "[" + sysStocks[k].CartonNo + "]:该条码零件号不在单据内!";
                    return rfInfo;
                }

                List<WmsOutstockSn> moveSnCreates = repository.GetOutStockSnByOrder(orderNo);
                if (moveSnCreates.Count > 0)
                {
                    List<WmsOutstockSn> wmsOutStockSns = repository.GetOutStockSnByOrderCartonNo(orderNo, sysStocks[k].CartonNo);
                    if (wmsOutStockSns.Count == 0)
                    {
                        rfInfo.type = "FAIL";
                        rfInfo.message = "单据中不包含此包装条码，不允许此操作！";
                        return rfInfo;
                    }
                }

                for (int i = 0; i < WmsOutstockDetails.Count; i++)
                {
                    int remainNum = Convert.ToInt32(WmsOutstockDetails[i].Qty - WmsOutstockDetails[i].OutQty);//余数
                    if (sysStocks[k].Qty == remainNum)
                    {
                        if (WmsOutstocks[0].OrderStatus != (int)WmsEnumUtil.MoveOrderDetailStatus.BATCHING)//
                        {
                            stringBuilder = new StringBuilder();
                            stringBuilder.Append("UPDATE wms_outstock SET order_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.BATCHING + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no='" + orderNo + "';");
                            sqlStrings.Add(stringBuilder.ToString());
                        }
                        stringBuilder = new StringBuilder();
                        stringBuilder.Append("UPDATE wms_outstock_detail SET out_qty+=" + sysStocks[k].Qty + ",item_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.COMPLETED + " ,update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  ruid='" + WmsOutstockDetails[i].Ruid + "';");
                        sqlStrings.Add(stringBuilder.ToString());

                        stringBuilder = new StringBuilder();
                        stringBuilder.Append("UPDATE sys_stock SET status=" + (int)WmsEnumUtil.StockStatus.SHIPPED + ",locate_id=0,locate_name='',zone_id=0,zone_name='',warehouse_id=0,warehouse_name='',update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  carton_no='" + sysStocks[k].CartonNo + "';");
                        sqlStrings.Add(stringBuilder.ToString());

                        stringBuilder = new StringBuilder();
                        //更新单据条码表
                        stringBuilder.Append("UPDATE dbo.wms_outstock_sn ");
                        stringBuilder.Append("SET status = " + (int)WmsEnumUtil.MoveOrderSnStatus.SHIPPED + ", ");
                        stringBuilder.Append("    update_userid = " + loginId + ", ");
                        stringBuilder.Append("    update_time = CONVERT(VARCHAR(20),GETDATE(),21) ");
                        stringBuilder.Append("WHERE order_no = '" + orderNo + "' ");
                        stringBuilder.Append("      AND carton_no = '" + sysStocks[k].CartonNo + "'; ");
                        sqlStrings.Add(stringBuilder.ToString());
                        break;
                    }
                    else if (sysStocks[k].Qty > remainNum)
                    {
                        rfInfo.type = "FAIL";
                        rfInfo.message = "[" + sysStocks[k].CartonNo + "]:该条码库存大于单据需求数量!";
                        return rfInfo;
                    }
                    else if (sysStocks[k].Qty < remainNum)
                    {
                        //处理中
                        if (WmsOutstocks[0].OrderStatus != (int)WmsEnumUtil.MoveOrderDetailStatus.BATCHING)//修改为盘点中状态
                        {
                            stringBuilder = new StringBuilder();
                            stringBuilder.Append("UPDATE wms_outstock SET order_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.BATCHING + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no='" + orderNo + "';");
                            sqlStrings.Add(stringBuilder.ToString());
                        }

                        stringBuilder = new StringBuilder();
                        stringBuilder.Append("UPDATE wms_outstock_detail SET out_qty+=" + sysStocks[k].Qty + ",item_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.COMPLETED + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  ruid='" + WmsOutstockDetails[i].Ruid + "';");
                        sqlStrings.Add(stringBuilder.ToString());

                        stringBuilder = new StringBuilder();
                        stringBuilder.Append("UPDATE sys_stock SET status=" + (int)WmsEnumUtil.StockStatus.SHIPPED + ",locate_id=0,locate_name='',zone_id=0,zone_name='',warehouse_id=0,warehouse_name='',update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  carton_no='" + sysStocks[k].CartonNo + "';");
                        sqlStrings.Add(stringBuilder.ToString());

                        stringBuilder = new StringBuilder();
                        //更新单据条码表
                        stringBuilder.Append("UPDATE dbo.wms_outstock_sn ");
                        stringBuilder.Append("SET status = " + (int)WmsEnumUtil.MoveOrderSnStatus.SHIPPED + ", ");
                        stringBuilder.Append("    update_userid = " + loginId + ", ");
                        stringBuilder.Append("    update_time = CONVERT(VARCHAR(20),GETDATE(),21) ");
                        stringBuilder.Append("WHERE order_no = '" + orderNo + "' ");
                        stringBuilder.Append("      AND carton_no = '" + sysStocks[k].CartonNo + "'; ");
                        sqlStrings.Add(stringBuilder.ToString());
                        break;
                    }

                }

                stringBuilder = new StringBuilder();
                stringBuilder.Append("INSERT INTO dbo.sys_stock_trans ");
                stringBuilder.Append("( ");
                stringBuilder.Append("    trans_code, ");
                stringBuilder.Append("    carton_no, ");
                stringBuilder.Append("    part_id, ");
                stringBuilder.Append("    part_no, ");
                stringBuilder.Append("    part_spec, ");
                stringBuilder.Append("    src_locate_id, ");
                stringBuilder.Append("    src_locate_name, ");
                stringBuilder.Append("    dest_locate_id, ");
                stringBuilder.Append("    dest_locate_name, ");
                stringBuilder.Append("    old_qty, ");
                stringBuilder.Append("    new_qty, ");
                stringBuilder.Append("    trans_qty, ");
                stringBuilder.Append("    old_status, ");
                stringBuilder.Append("    new_status, ");
                stringBuilder.Append("    unit, ");
                stringBuilder.Append("    factory_id, ");
                stringBuilder.Append("    factory_code, ");
                stringBuilder.Append("    src_erp_warehouse, ");
                stringBuilder.Append("    dest_erp_warehouse, ");
                stringBuilder.Append("    src_warehouse_id, ");
                stringBuilder.Append("    src_warehouse_name, ");
                stringBuilder.Append("    dest_warehouse_id, ");
                stringBuilder.Append("    dest_warehouse_name, ");
                stringBuilder.Append("    src_zone_id, ");
                stringBuilder.Append("    src_zone_name, ");
                stringBuilder.Append("    dest_zone_id, ");
                stringBuilder.Append("    dest_zone_name, ");
                stringBuilder.Append("    enabled, ");
                stringBuilder.Append("    create_userid, ");
                stringBuilder.Append("    create_time, ");
                stringBuilder.Append("    update_userid, ");
                stringBuilder.Append("    update_time, ");
                stringBuilder.Append("    guid ");
                stringBuilder.Append(") ");
                stringBuilder.Append("VALUES ");
                stringBuilder.Append("(   '" + (int)WmsEnumUtil.TransType.OUTWARD_SHIPMENT + "', ");//销售发运
                stringBuilder.Append("    '" + sysStocks[k].CartonNo + "', ");
                stringBuilder.Append("    " + sysStocks[k].PartId + ", ");
                stringBuilder.Append("    '" + sysStocks[k].PartNo + "',  ");
                stringBuilder.Append("    N'" + sysStocks[k].PartSpec + "', ");
                stringBuilder.Append("    " + sysStocks[k].LocateId + ",  ");//源库位
                stringBuilder.Append("    '" + sysStocks[k].LocateName + "',  ");
                stringBuilder.Append("    0, ");//目标库位
                stringBuilder.Append("    '',  ");
                stringBuilder.Append("    " + sysStocks[k].Qty + ",");
                stringBuilder.Append("    " + sysStocks[k].Qty + ",");
                stringBuilder.Append("    " + sysStocks[k].Qty + ",");
                stringBuilder.Append("    '" + sysStocks[k].Status + "', ");
                stringBuilder.Append("    '" + (int)WmsEnumUtil.StockStatus.SHIPPED + "', ");//已发运
                stringBuilder.Append("    '" + sysStocks[k].Unit + "', ");
                stringBuilder.Append("    " + sysStocks[k].FactoryId + ", ");
                stringBuilder.Append("    '" + sysStocks[k].FactoryCode + "',");
                stringBuilder.Append("    '" + sysStocks[k].ErpWarehouse + "',");
                stringBuilder.Append("    '" + sysStocks[k].ErpWarehouse + "', ");
                stringBuilder.Append("    " + sysStocks[k].WarehouseId + ", ");
                stringBuilder.Append("    '" + sysStocks[k].WarehouseName + "', ");
                stringBuilder.Append("    0, ");
                stringBuilder.Append("    '', ");
                stringBuilder.Append("    " + sysStocks[k].ZoneId + ",  ");
                stringBuilder.Append("    '" + sysStocks[k].ZoneName + "',  ");
                stringBuilder.Append("    0, ");
                stringBuilder.Append("    '',  ");
                stringBuilder.Append("    'Y', ");
                stringBuilder.Append("    " + loginId + ", ");
                stringBuilder.Append("    CONVERT(VARCHAR(20),GETDATE(),21), ");
                stringBuilder.Append("    " + loginId + ", ");
                stringBuilder.Append("    CONVERT(VARCHAR(20),GETDATE(),21), ");
                stringBuilder.Append("    NEWID()  ");
                stringBuilder.Append("    ) ; ");
                sqlStrings.Add(stringBuilder.ToString());

            }

            int updateNum = repository.SQLTransaction(sqlStrings, parameterList);
            if (updateNum > 0)
            {
                List<WmsOutstockDetail> wmsMoves1 = repository.GetOutStockDetailByOrder(orderNo);
                for (int i = 0; i < wmsMoves1.Count; i++)
                {
                    if (wmsMoves1[i].PickQty != wmsMoves1[i].OutQty)
                    {
                        rfInfo.type = "PASS";
                        rfInfo.message = "操作成功!请继续扫描箱条码";
                        rfInfo.wmsObjectDetail = wmsMoves1.ConvertAll(s => (object)s);
                        return rfInfo;
                    }
                }
              
                int updateStatus = 1;
                sqlStrings = new List<string>();
                parameterList = new List<DynamicParameters>();
                StringBuilder SqlStringBuilder = new StringBuilder(1024);
                DynamicParameters parameters = new DynamicParameters();

                List<WmsOutstockDetail> wmsOutstockDetails = repository.GetFinishOutStockDetailByOrderNo(orderNo);
                if (wmsOutstockDetails.Count > 0)
                {
                    if (wmsOutstockDetails[0].OrderType == (int)WmsEnumUtil.OutStockType.SALE_SHIPPING)//JIS  WMS创建的销售发运单据类型
                    {
                        //WMS将每次发运的信息传递给SAP,SAP用于创建交货单。 JIS
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("INSERT INTO dbo.WMS_JIS(ZZ_WMSNUM,WERKS,LGORT,LFDAT,KUNNR,MATNR ");
                        SqlStringBuilder.Append("           ,LFIMG,MEINS,ZPOST,ZTIME,SID,RECTIM,SYNFLG,GUID) ");
                        SqlStringBuilder.Append("     VALUES(@ZZ_WMSNUM,@WERKS,@LGORT,@LFDAT,@KUNNR,@MATNR,@LFIMG ");
                        SqlStringBuilder.Append("           ,@MEINS,@ZPOST,@ZTIME,@SID,@RECTIM,@SYNFLG,@GUID) ");


                        for (int i = 0; i < wmsOutstockDetails.Count; i++)
                        {
                            SysPart sysPart = repository.GetPartNOInfoByPartNo(wmsOutstockDetails[i].PartNo);
                            sqlStrings.Add(SqlStringBuilder.ToString());
                            parameters = new DynamicParameters();
                            parameters.Add("@ZZ_WMSNUM", wmsOutstockDetails[i].OrderNo);//WMS发运单据号
                            parameters.Add("@WERKS", wmsOutstockDetails[i].FactoryCode);//发货工厂
                            parameters.Add("@LGORT", wmsOutstockDetails[i].SrcErpWarehouse);//发货库存地
                            parameters.Add("@LFDAT", string.IsNullOrEmpty(wmsOutstockDetails[i].PlanDate) ? "" : Convert.ToDateTime(wmsOutstockDetails[i].PlanDate).ToString("yyyyMMdd"));//交货日期
                            parameters.Add("@KUNNR", wmsOutstockDetails[i].CustomerCode);//客户编码（送达方）
                            parameters.Add("@MATNR", wmsOutstockDetails[i].PartNo);//物料号
                            parameters.Add("@LFIMG", wmsOutstockDetails[i].OutQty);//交货数量
                            if (sysPart == null)
                            {
                                parameters.Add("@MEINS", "");//计量单位
                            }
                            else
                            {
                                parameters.Add("@MEINS", sysPart.Unit);//计量单位
                            }
                            parameters.Add("@ZPOST", DateTime.Now.ToString("yyyyMMdd"));//交易日期
                            parameters.Add("@ZTIME", DateTime.Now.ToString("HHmmss"));//交易时间
                            parameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
                            parameters.Add("@RECTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            parameters.Add("@SYNFLG", "N");
                            parameters.Add("@GUID", Guid.NewGuid().ToString());
                            parameterList.Add(parameters);
                        }
                    }
                    else if (wmsOutstockDetails[0].OrderType == (int)WmsEnumUtil.OutStockType.SALE_SHIPPING_NJIS)//非JIS SAP传递的销售发运单据类型
                    {
                        //WMS将每次发运的信息传递给SAP,SAP用于对交货单发货。
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("INSERT INTO dbo.WMS_NJSI(VBELN,POSNR,WERKS,LGORT,BLDAT,KUNNR,MATNR,LFIMG ");
                        SqlStringBuilder.Append("           ,MEINS,ZDATE,ZTIME,SID,RECTIM,SYNFLG,GUID) ");
                        SqlStringBuilder.Append("     VALUES(@VBELN,@POSNR,@WERKS,@LGORT,@BLDAT,@KUNNR,@MATNR,@LFIMG ");
                        SqlStringBuilder.Append("           ,@MEINS,@ZDATE,@ZTIME,@SID,@RECTIM,@SYNFLG,@GUID) ");

                        for (int i = 0; i < wmsOutstockDetails.Count; i++)
                        {
                            SysPart sysPart = repository.GetPartNOInfoByPartNo(wmsOutstockDetails[i].PartNo);
                            sqlStrings.Add(SqlStringBuilder.ToString());
                            parameters = new DynamicParameters();
                            parameters.Add("@VBELN", wmsOutstockDetails[i].OrderNo);//销售交货单
                            parameters.Add("@POSNR", (i + 1) * 10);//行项目号
                            parameters.Add("@WERKS", wmsOutstockDetails[i].FactoryCode);//发货工厂
                            parameters.Add("@LGORT", wmsOutstockDetails[i].SrcErpWarehouse);//发货库存地
                            parameters.Add("@BLDAT", string.IsNullOrEmpty(wmsOutstockDetails[i].PlanDate) ? "" : Convert.ToDateTime(wmsOutstockDetails[i].PlanDate).ToString("yyyyMMdd"));//交货日期
                            parameters.Add("@KUNNR", wmsOutstockDetails[i].CustomerCode);//客户编码（送达方）
                            parameters.Add("@MATNR", wmsOutstockDetails[i].PartNo);//物料编码
                            parameters.Add("@LFIMG", wmsOutstockDetails[i].OutQty);//转储数量
                            if (sysPart == null)
                            {
                                parameters.Add("@MEINS", "");//计量单位
                            }
                            else
                            {
                                parameters.Add("@MEINS", sysPart.Unit);//计量单位
                            }
                            parameters.Add("@ZPOST", DateTime.Now.ToString("yyyyMMdd"));//交易日期
                            parameters.Add("@ZTIME", DateTime.Now.ToString("HHmmss"));//交易时间
                            parameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
                            parameters.Add("@RECTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            parameters.Add("@SYNFLG", "N");
                            parameters.Add("@GUID", Guid.NewGuid().ToString());
                            parameterList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("UPDATE wms_outstock SET order_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.COMPLETED + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no=@orderNo;");
                    sqlStrings.Add(SqlStringBuilder.ToString());
                    parameters = new DynamicParameters();
                    parameters.Add("@orderNo", orderNo);
                    parameterList.Add(parameters);

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("UPDATE wms_outstock_detail SET item_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.COMPLETED + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no=@orderNo;");
                    sqlStrings.Add(SqlStringBuilder.ToString());
                    parameters = new DynamicParameters();
                    parameters.Add("@orderNo", orderNo);
                    parameterList.Add(parameters);

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("UPDATE wms_outstock_sn SET status=" + (int)WmsEnumUtil.MoveOrderSnStatus.PROCESSED + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no=@orderNo;");
                    sqlStrings.Add(SqlStringBuilder.ToString());
                    parameters = new DynamicParameters();
                    parameters.Add("@orderNo", orderNo);
                    parameterList.Add(parameters);

                    updateStatus = repository.SQLTransaction(sqlStrings, parameterList);
                }
                if (updateStatus > 0)
                {
                    rfInfo.type = "PASS";
                    rfInfo.message = "单据操作完成!";
                    return rfInfo;
                }
                else
                {
                    rfInfo.type = "FAIL";
                    rfInfo.message = "单据操作操作失败!请检查";
                    return rfInfo;
                }
            }
            else
            {
                //提示  操作失败!
                rfInfo.type = "FAIL";
                rfInfo.message = "操作失败，请检查！";
            }

            return rfInfo;
        }
        public SetObjectDetail SetSaleDeliveryOrderNoSubmit(string orderNo, string loginId)
        {
            SetObjectDetail rfInfo = new SetObjectDetail();//返回消息

            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();

            StringBuilder SqlStringBuilder = new StringBuilder(1024);
            DynamicParameters parameters = new DynamicParameters();
            int updateStatus = 1;
            WmsOutstockDetail wmsOutstocks = repository.GetOutStockDetailQtySumByOrder(orderNo);
            if (wmsOutstocks.PickQty == wmsOutstocks.OutQty)
            {
                List<WmsOutstockDetail> wmsOutstockDetails = repository.GetFinishOutStockDetailByOrderNo(orderNo);
                if (wmsOutstockDetails.Count > 0)
                {
                    if (wmsOutstockDetails[0].OrderType == (int)WmsEnumUtil.OutStockType.SALE_SHIPPING)//JIS  WMS创建的销售发运单据类型
                    {
                        //WMS将每次发运的信息传递给SAP,SAP用于创建交货单。 JIS
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("INSERT INTO dbo.WMS_JIS(ZZ_WMSNUM,WERKS,LGORT,LFDAT,KUNNR,MATNR ");
                        SqlStringBuilder.Append("           ,LFIMG,MEINS,ZPOST,ZTIME,SID,RECTIM,SYNFLG,GUID) ");
                        SqlStringBuilder.Append("     VALUES(@ZZ_WMSNUM,@WERKS,@LGORT,@LFDAT,@KUNNR,@MATNR,@LFIMG ");
                        SqlStringBuilder.Append("           ,@MEINS,@ZPOST,@ZTIME,@SID,@RECTIM,@SYNFLG,@GUID) ");

                        for (int i = 0; i < wmsOutstockDetails.Count; i++)
                        {
                            SysPart sysPart = repository.GetPartNOInfoByPartNo(wmsOutstockDetails[i].PartNo);
                            sqlStrings.Add(SqlStringBuilder.ToString());
                            parameters = new DynamicParameters();
                            parameters.Add("@ZZ_WMSNUM", wmsOutstockDetails[i].OrderNo);//WMS发运单据号
                            parameters.Add("@WERKS", wmsOutstockDetails[i].FactoryCode);//发货工厂
                            parameters.Add("@LGORT", wmsOutstockDetails[i].SrcErpWarehouse);//发货库存地
                            parameters.Add("@LFDAT",string.IsNullOrEmpty(wmsOutstockDetails[i].PlanDate)?"":Convert.ToDateTime(wmsOutstockDetails[i].PlanDate).ToString("yyyyMMdd"));//交货日期
                            parameters.Add("@KUNNR", wmsOutstockDetails[i].CustomerCode);//客户编码（送达方）
                            parameters.Add("@MATNR", wmsOutstockDetails[i].PartNo);//物料号
                            parameters.Add("@LFIMG", wmsOutstockDetails[i].OutQty);//交货数量
                            if (sysPart == null)
                            {
                                parameters.Add("@MEINS", "");//计量单位
                            }
                            else
                            {
                                parameters.Add("@MEINS", sysPart.Unit);//计量单位
                            }
                            parameters.Add("@ZPOST", DateTime.Now.ToString("yyyyMMdd"));//交易日期
                            parameters.Add("@ZTIME", DateTime.Now.ToString("HHmmss"));//交易时间
                            parameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
                            parameters.Add("@RECTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            parameters.Add("@SYNFLG", "N");
                            parameters.Add("@GUID", Guid.NewGuid().ToString());
                            parameterList.Add(parameters);
                        }

                    }
                    else if (wmsOutstockDetails[0].OrderType == (int)WmsEnumUtil.OutStockType.SALE_SHIPPING_NJIS)//非JIS SAP传递的销售发运单据类型
                    {
                        //WMS将每次发运的信息传递给SAP,SAP用于对交货单发货。
                        SqlStringBuilder = new StringBuilder(1024);
                        SqlStringBuilder.Append("INSERT INTO dbo.WMS_NJSI(VBELN,POSNR,WERKS,LGORT,BLDAT,KUNNR,MATNR,LFIMG ");
                        SqlStringBuilder.Append("           ,MEINS,ZDATE,ZTIME,SID,RECTIM,SYNFLG,GUID) ");
                        SqlStringBuilder.Append("     VALUES(@VBELN,@POSNR,@WERKS,@LGORT,@BLDAT,@KUNNR,@MATNR,@LFIMG ");
                        SqlStringBuilder.Append("           ,@MEINS,@ZDATE,@ZTIME,@SID,@RECTIM,@SYNFLG,@GUID) ");

                        for (int i = 0; i < wmsOutstockDetails.Count; i++)
                        {
                            SysPart sysPart = repository.GetPartNOInfoByPartNo(wmsOutstockDetails[i].PartNo);
                            sqlStrings.Add(SqlStringBuilder.ToString());
                            parameters = new DynamicParameters();
                            parameters.Add("@VBELN", wmsOutstockDetails[i].OrderNo);//销售交货单
                            parameters.Add("@POSNR", (i + 1) * 10);//行项目号
                            parameters.Add("@WERKS", wmsOutstockDetails[i].FactoryCode);//发货工厂
                            parameters.Add("@LGORT", wmsOutstockDetails[i].SrcErpWarehouse);//发货库存地
                            parameters.Add("@BLDAT", string.IsNullOrEmpty(wmsOutstockDetails[i].PlanDate) ? "" : Convert.ToDateTime(wmsOutstockDetails[i].PlanDate).ToString("yyyyMMdd"));//交货日期
                            parameters.Add("@KUNNR", wmsOutstockDetails[i].CustomerCode);//客户编码（送达方）
                            parameters.Add("@MATNR", wmsOutstockDetails[i].PartNo);//物料编码
                            parameters.Add("@LFIMG", wmsOutstockDetails[i].OutQty);//转储数量
                            if (sysPart == null)
                            {
                                parameters.Add("@MEINS", "");//计量单位
                            }
                            else
                            {
                                parameters.Add("@MEINS", sysPart.Unit);//计量单位
                            }
                            parameters.Add("@ZPOST", DateTime.Now.ToString("yyyyMMdd"));//交易日期
                            parameters.Add("@ZTIME", DateTime.Now.ToString("HHmmss"));//交易时间
                            parameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
                            parameters.Add("@RECTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            parameters.Add("@SYNFLG", "N");
                            parameters.Add("@GUID", Guid.NewGuid().ToString());
                            parameterList.Add(parameters);
                        }
                    }

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("UPDATE wms_outstock SET order_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.COMPLETED + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no=@orderNo;");
                    sqlStrings.Add(SqlStringBuilder.ToString());
                    parameters = new DynamicParameters();
                    parameters.Add("@orderNo", orderNo);
                    parameterList.Add(parameters);

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("UPDATE wms_outstock_detail SET item_status=" + (int)WmsEnumUtil.MoveOrderDetailStatus.COMPLETED + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no=@orderNo;");
                    sqlStrings.Add(SqlStringBuilder.ToString());
                    parameters = new DynamicParameters();
                    parameters.Add("@orderNo", orderNo);
                    parameterList.Add(parameters);

                    SqlStringBuilder = new StringBuilder(1024);
                    SqlStringBuilder.Append("UPDATE wms_outstock_sn SET status=" + (int)WmsEnumUtil.MoveOrderSnStatus.PROCESSED + ",update_userid=" + loginId + ",update_time=CONVERT(VARCHAR(20),GETDATE(),21) WHERE  order_no=@orderNo;");
                    sqlStrings.Add(SqlStringBuilder.ToString());
                    parameters = new DynamicParameters();
                    parameters.Add("@orderNo", orderNo);
                    parameterList.Add(parameters);

                    updateStatus = repository.SQLTransaction(sqlStrings, parameterList);
                }
                if (updateStatus > 0)
                {
                    rfInfo.type = "PASS";
                    rfInfo.message = "[" + orderNo + "]单据已提交，请重新选择单据";
                }
                else
                {
                    rfInfo.type = "FAIL";
                    rfInfo.message = "未查询到数据，请检查！";
                }
            }
            else
            {
                rfInfo.type = "FAIL";
                rfInfo.message = "[" + orderNo + "]该单据配料数未完全发运，请检查！";
            }

            return rfInfo;
        }
    }
}
